from PyQt5.QtWidgets import QDialog, QFileDialog

from tool.comm import Tool
from window.config_window import Ui_config


class config_set(Ui_config, QDialog):
    def __init__(self):
        super(Ui_config, self).__init__()
        self.setupUi(self)
        self.setModal(True)
        self.bind_event()
        self.work_path_value = None  # 工作路径输入
        self.work_svn_path_value = None  # svn 路径
        self.load_config()

    def bind_event(self):
        self.btn_cancel.clicked.connect(self.close)
        self.btn_ok.clicked.connect(self.save_config)
        self.open_path.clicked.connect(self.select_dir)

    def load_config(self):
        self.work_path_value = Tool.get_config_by_key("work_path")
        self.work_svn_path_value = Tool.get_config_by_key("svn_path")
        self.set_edit_value()

    def set_edit_value(self):
        self.work_svn_path.setText(self.work_svn_path_value)
        self.work_path.setText(self.work_path_value)
        self.work_svn_path.textEdited.connect(lambda v: self.disable_btn(v))

    def disable_btn(self, value):
        if Tool.str_not_empty(value) and Tool.re_is_url(value):
            tag = True
        else:
            tag = False
        self.btn_ok.setEnabled(tag)

    def select_dir(self):
        dirs = QFileDialog.getExistingDirectory(self, "选择工作文件夹", )
        print("路径", dirs)
        not_empty = Tool.str_not_empty(dirs)
        if not_empty:
            self.work_path_value = dirs
            self.set_edit_value()

    def save_config(self):
        _path = self.work_path.text()
        _path_svn = self.work_svn_path.text()
        if Tool.str_not_empty(_path) and Tool.str_not_empty(_path_svn):
            if Tool.re_is_path(_path) and Tool.re_is_url(_path_svn):
                self.work_path_value = _path
                Tool.save_config({
                    "work_path": _path,
                    "svn_path": _path_svn
                })
                self.close()
